package com.xframe.xdal.core.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class FileUtil {


    public static List<String> readDirectoryName(String basePath){
        File file = new File(basePath);
        File[] files = file.listFiles();
        List<String> dirs = new ArrayList<>();
        for(int i = 0; i < files.length; i++){
            if(files[i].isDirectory()){
                dirs.add(files[i].getName());
            }
        }
        return dirs;
    }

    public static List<String> readFileName(String basePath){
        File file = new File(basePath);
        File[] files = file.listFiles();
        List<String> fileList = new ArrayList<>();
        for(int i = 0; i < files.length; i++){
            if(files[i].isFile()){
                fileList.add(files[i].getName());
            }
        }
        return fileList;
    }

    public static Map readFileGetJson(String path, String language, String version, String fileName){
        StringBuilder fileBuilder = new StringBuilder(path).append(File.separator).append(language).append(File.separator).append(version).append(File.separator);
        String fullPathName = fileBuilder + File.separator + fileName;
        return readFileGetJson(fullPathName);
    }

    public static Map readFileGetJson(String fileFullPathName){
        InputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(fileFullPathName));
            String conf = IOUtils.toString(in, StandardCharsets.UTF_8);
            JSONObject jsonObject = JSON.parseObject(conf);
            String json = JSON.toJSONString(jsonObject);
            Map map = JSONObject.parseObject(json, Map.class);
            return map;
        }catch (IOException e) {
            return null;
        }finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



}
